using SG3L_RAG.Application.Interfaces;
using SG3L_RAG.Domain.Entities;
using SG3L_RAG.Domain.Repositories;

namespace SG3L_RAG.Application.Services
{
    public class MessageService : IMessageService
    {
        private readonly IRepository<Message> _messageRepository;

        public MessageService(IRepository<Message> messageRepository)
        {
            _messageRepository = messageRepository;
        }

        public async Task<Message?> GetByIdAsync(Guid id)
        {
            return await _messageRepository.GetByIdAsync(id);
        }

        public async Task<IEnumerable<Message>> GetAllAsync()
        {
            return await _messageRepository.GetAllAsync();
        }

        public async Task<Message> CreateAsync(Guid conversationId, string sender, string content, string reply, Guid? referencedDocId = null)
        {
            var message = Message.Create(conversationId, sender, content, reply, referencedDocId);
            await _messageRepository.AddAsync(message);
            return message;
        }

        public async Task UpdateAsync(Message message)
        {
            await _messageRepository.UpdateAsync(message);
        }

        public async Task DeleteAsync(Guid id)
        {
            await _messageRepository.DeleteAsync(id);
        }

        public async Task<IEnumerable<Message>> GetByConversationIdAsync(Guid conversationId)
        {
            var messages = await _messageRepository.GetAllAsync();
            return messages.Where(m => m.ConversationId == conversationId);
        }

        public async Task<IEnumerable<Message>> GetBySenderAsync(string sender)
        {
            var messages = await _messageRepository.GetAllAsync();
            return messages.Where(m => m.Sender == sender);
        }

        public async Task<IEnumerable<Message>> GetMessagesWithDocumentReferenceAsync(Guid documentId)
        {
            var messages = await _messageRepository.GetAllAsync();
            return messages.Where(m => m.ReferencedDocId == documentId);
        }

        public async Task<Message?> GetLatestMessageAsync(Guid conversationId)
        {
            var messages = await GetByConversationIdAsync(conversationId);
            return messages.OrderByDescending(m => m.CreatedAt).FirstOrDefault();
        }

        public async Task<IEnumerable<Message>> GetRecentMessagesAsync(Guid conversationId, int count = 50)
        {
            var messages = await GetByConversationIdAsync(conversationId);
            return messages.OrderByDescending(m => m.CreatedAt).Take(count);
        }

        public async Task UpdateReplyAsync(Guid messageId, string reply)
        {
            var message = await _messageRepository.GetByIdAsync(messageId);
            if (message != null)
            {
                message.UpdateReply(reply);
                await _messageRepository.UpdateAsync(message);
            }
        }
    }
}
